<?php

namespace app\common\model;


use think\Model;
use traits\model\SoftDelete;

class ScenicComment extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $name = 'scenic_comment';


    public function answer()
    {
        return $this->belongsTo('app\store\model\scenic\Answer','id','comment_id');
    }
    
    /**
     * [getComment 商家评价列表]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-23
     * @param    array       $where [description]
     * @param    array       $field [description]
     * @param    integer     $page  [description]
     * @return   [type]             [description]
     */
    public static function getComment($where = [], $field = [], $page = 0)
    {
        $field = $field ? $field : '*';
        $limit = $page ? 10 : 4;

        $list = self::where($where)
                    ->with(['answer'])
                    ->alias('a')
                    ->join('user b', 'a.user_id = b.id')
                    ->field($field)
                    ->order('mark desc,images desc,a.create_time desc')
                    ->where('a.status','normal')
                    ->page($page, $limit)
                    ->select();
        $list = $list ? collection($list)->toArray() : [];
        foreach ($list as &$comment) {
            $comment['answer']['create_time'] =$comment['answer'] ? datetime($comment['answer']['create_time']) : null;
            $comment['create_time'] = date('Y-m-d H:i:s', $comment['create_time']);
           if ($comment['images']){
               $comment['images'] = explode(',', $comment['images']);
           }else{
               $comment['images'] = [];
           }

        }

        if (array_key_exists('mark', $where)) {
            unset($where['mark']);
        }
        $avg = self::where($where)->avg('mark');
        $data['avg_mark'] = round($avg,1);
        $data['count'] = self::where('scenic_id', $where['scenic_id'])->count();
        $data['comment_list'] = $list;
        return $data;
    }


}